<template>
  <a-modal
    title="导入EXCEL"
    :width="600"
    :visible="visible"
    :confirmLoading="uploading"
    @cancel="handleClose">

    <a-form-model ref="form" :rules="validatorRules" :model="form" v-bind="formItemLayout">
      <a-form-model-item label="是否开启校验" v-if="online" style="margin-bottom: 0;">
        <a-switch :checked="validateStatus==1" @change="handleChangeValidateStatus" checked-children="是" un-checked-children="否" size="small"/>
      </a-form-model-item>
      <a-form-model-item label="附件" prop="fileList" style="margin-bottom: 0;">
        <a-upload
          name="file"
          :multiple="true"
          accept=".xls,.xlsx"
          :fileList="form.fileList"
          :remove="handleRemove"
          :beforeUpload="beforeUpload">
          <a-button>
            <a-icon type="upload" />
            选择导入文件
          </a-button>
        </a-upload>
        <p style="margin: 0;">支持扩展名：.xls，.xlsx</p>
      </a-form-model-item>
      <a-form-model-item label="角色" prop="roles" style="margin-bottom: 0;" v-if="rolesOptions && rolesOptions.length>0">
        <a-select mode="multiple" v-model="form.roles" :options="rolesOptions" placeholder="请选择" />
      </a-form-model-item>
    </a-form-model>
    <template slot="footer">
      <a-button @click="handleClose">关闭</a-button>
      <a-button type="primary" @click="handleImport" :disabled="buttonStatus" :loading="uploading"> {{ uploading ? '上传中...' : '开始上传' }} </a-button>
    </template>

  </a-modal>
</template>

<script>
  import { postAction } from '@/api/manage'
  export default {
    name: 'ImportModal',
    props: {
      url: {
        type: String,
        default: '',
        required: false
      },
      biz: {
        type: String,
        default: '',
        required: false
      },
      rolesOptions: {
        type: Array,
        default: []
      },
      // 是否online导入
      online: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data() {
      return {
        visible: false,
        uploading: false,
        uploadAction: '',
        foreignKeys: '',
        validateStatus: 0,
        form: {
          fileList: [],
          roles: []
        },
        formItemLayout: {
          labelCol: { span: 4 },
          wrapperCol: { span: 18 }
        },
        validatorRules: {
          fileList: [{ required: true, message: '请选择文件' }],
          roles: [{ required: true, message: '请选择角色' }]
        }
      }
    },
    watch: {
      url (val) {
        if (val) {
         this.uploadAction = val
        //  this.uploadAction = window._CONFIG['domianURL']+val
        }
      }
    },
    computed: {
      buttonStatus() {
        let bool = false
        if (this.form.fileList.length === 0 || this.form.roles.length === 0) {
          bool = true
        }
        return bool
      }
    },
    created () {
      this.uploadAction = this.url
      // this.uploadAction = window._CONFIG['domianURL']+this.url
    },
    methods: {
      handleClose() {
        this.visible = false
      },
      show(arg) {
        this.form.fileList = []
        this.form.roles = []
        this.uploading = false
        this.visible = true
        this.foreignKeys = arg
        this.validateStatus = 0
      },
      handleRemove(file) {
        const index = this.form.fileList.indexOf(file)
        const newFileList = this.form.fileList.slice()
        newFileList.splice(index, 1)
        this.form.fileList = newFileList
      },
      beforeUpload(file) {
        this.form.fileList = [...this.form.fileList, file]
        return false
      },
      handleImport() {
        const { fileList, roles } = this.form
        const formData = new FormData()
        if (this.biz) {
          formData.append('isSingleTableImport', this.biz)
        }
        if (this.foreignKeys && this.foreignKeys.length > 0) {
          formData.append('foreignKeys', this.foreignKeys)
        }
        if (this.online == true) {
          formData.append('validateStatus', this.validateStatus)
        }
        fileList.forEach((file) => {
          formData.append('file', file)
          // formData.append('files[]', fileld);
        })
        if (this.rolesOptions && this.rolesOptions.length > 0) {
          formData.append('roles', roles.join(','))
        }
        this.$refs.form.validate(valid => {
          if (valid) {
            this.uploading = true
            postAction(this.uploadAction, formData).then((res) => {
              this.uploading = false
              if (res.success) {
                if (res.code == 201) {
                  this.errorTip(res.message, res.result)
                } else {
                  this.$message.success(res.message)
                }
                this.visible = false
                this.$emit('ok')
              } else {
                if (res.code == 500) {
                  let result = Array.isArray(res.result) ? res.result.join('<br>') : res.result
                  this.$error({
                    title: res.message ? res.message : '提示',
                    content: h => <span domPropsInnerHTML={result} />
                  })
                } else {
                  this.$message.warning(res.message)
                }
              }
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      // 是否开启校验 开关改变事件
      handleChangeValidateStatus(checked) {
        this.validateStatus = checked == true ? 1 : 0
      },
      // 错误信息提示
      errorTip(tipMessage, fileUrl) {
        const h = this.$createElement
        let href = window._CONFIG['domianURL'] + fileUrl
        this.$warning({
          title: '导入成功,但是有错误数据!',
          content: h('div', {}, [
            h('div', tipMessage),
            h('span', '具体详情请 '),
            h('a', {
              attrs: {
                href: href,
                target: '_blank'
              }
            }, '点击下载')
          ]),
          onOk() {}
        })
      }

    }
  }
</script>

<style scoped>

</style>
